package com.jt.antiFakeSys.api;

import com.jt.antiFakeSys.Constants;
import com.jt.antiFakeSys.model.AntiFakeCode;
import com.jt.antiFakeSys.service.AntiFakeCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;


/**
 * 防伪码(AntiFakeCode)表控制层
 *
 * @author longhp
 * @since 2019-03-02 13:24:37
 */
@Controller
@Slf4j
public class AntiFakeCodeApiController {

    @Resource
    private AntiFakeCodeService antiFakeCodeService;
    @RequestMapping("/index.php")
    public String getShareCode(HttpServletRequest httpServletRequest,
                               ModelMap map) {
        String s = httpServletRequest.getParameter("s");
        if(StringUtils.isEmpty(s)){
            return "error";
        }
        String code = getCode(s);
        if(StringUtils.isEmpty(code)){
            return "error";
        }
        Example example = new Example(AntiFakeCode.class);
        example.createCriteria().andEqualTo("code",code)
                                .andLessThan("searchNum",10)
                                .andEqualTo("status", Constants.FLAG_YSE);
        List<AntiFakeCode> list = antiFakeCodeService.selectListByExample(example);
        if(list==null||list.isEmpty()){
            return "error";
        }
        AntiFakeCode antiFakeCode = list.get(0);
        Integer searchNum = antiFakeCode.getSearchNum()==null?1:antiFakeCode.getSearchNum()+1;
        Date firstSearchTime = antiFakeCode.getFirstSearchTime();
        if(searchNum==1||firstSearchTime==null){
             firstSearchTime = new Date();
            antiFakeCode.setFirstSearchTime(firstSearchTime);
        }
        map.put("searchNum",searchNum);
        map.put("firstSearchTime", DateFormatUtils.format(firstSearchTime,"yyyy-MM-dd HH:mm:ss"));
        map.put("code",antiFakeCode.getCode());
        map.put("validateTime", DateFormatUtils.format(antiFakeCode.getValidateTime(),"yyyy-MM-dd"));
        antiFakeCode.setSearchNum(searchNum);
        antiFakeCodeService.update(antiFakeCode);
        return "index";
    }

    private String getCode(String s){
        String[] ss = s.split("/");
        String code = ss[ss.length-1];
        if(StringUtils.isNumeric(code)){
            return code;
        }else {
            return null;
        }
    }
}